package cn.edu.fzu.homemaking.dfa;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public final class DfaUtil {

    private static final CacheLoader<Collection<String>, DfaTree>  loader =
            // 构建 DfaTree 比较耗时, 缓存起来重用
            new CacheLoader<Collection<String>, DfaTree>() {
                @Override
                public DfaTree load(Collection<String> key) throws Exception {
                    return new DfaTree(key);
                }
            };

    private static final LoadingCache<Collection<String>, DfaTree> cache  = CacheBuilder.newBuilder()
            .expireAfterAccess(24, TimeUnit.HOURS).build(loader);


    private DfaUtil() {

    }


    public static final boolean match(String text, Collection<String> keywords) {
        return cache.getUnchecked(keywords).match(text, false).match;
    }


    public static final Set<String> find(String text, Collection<String> keywords) {
        return cache.getUnchecked(keywords).match(text, true).allString;
    }

}
